<!--
 * @Author: 小花
 * @Date: 2022-04-22 20:16:31
 * @LastEditors: 小花
 * @LastEditTime: 2022-05-16 23:02:41
 * @FilePath: /vue3-teap/src/components/AddWorkers.vue
 * @Description:
-->
<template>
  <el-drawer v-model="drawerVisible" direction="btt" size="85%">
    <template #title>
      <h4>批量新增维修员</h4>
    </template>
    <template #default>
      <el-upload :accept="'.xls, .xlsx'" action="undefined" class="upload-demo" :auto-upload="false"
        :on-change="fileSelect">
        <template #trigger>
          <el-button>导入</el-button>
        </template>
      </el-upload>
      <el-divider />
      <el-table :data="baseTable" style="width: 100%">
        <el-table-column type="index" width="50" />
        <el-table-column label="姓名" prop="workerName" />
        <el-table-column label="电话" prop="workerPhone" />
        <el-table-column label="邮箱" prop="workerEmail" />
      </el-table>
    </template>
    <template #footer>
      <div class="footer">
        <el-button @click="cancel">取消
        </el-button>
        <el-button type="primary" @click="confirm">新增
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs } from 'vue'
import AddWorkersData from '@/model/main/layout/dynamicNav/WorkerPage/AddWorkers'
import { ElMessage, ElNotification, UploadFile } from 'element-plus'
import { importExcelFromBuffer, replaceTitle } from '@/plugins/xlsx/xlsx'
import { IWorker } from '@/model/main/layout/dynamicNav/WorkerPage'
import { addNewWorkers } from '@/plugins/request/http'
import { responseEnum, responseUtil } from '@/plugins/request/responseUtil'
import nProgress from 'nprogress'

export default defineComponent({
  name: 'addWorkers',
  setup () {
    const coreData = reactive(new AddWorkersData())

    async function fileSelect (uploadFile: UploadFile) {
      if (!uploadFile.raw) return
      const arrayBuffer = await uploadFile.raw.arrayBuffer()
      const json = importExcelFromBuffer<IWorker>(arrayBuffer)
      const title = {
        姓名: 'workerName',
        电话: 'workerPhone',
        邮箱: 'workerEmail'
      }
      replaceTitle(json, title)
      coreData.baseTable = coreData.baseTable.concat(json)
    }

    function cancel () {
      coreData.baseTable.length = 0
      coreData.drawerVisible = false
    }

    async function confirm () {
      nProgress.start()
      const result = await (await addNewWorkers(coreData.baseTable)).data as responseUtil
      if (result.code === responseEnum.OK) {
        coreData.drawerVisible = false
        ElNotification.success({
          title: 'Success',
          message: result.msg
        })
      } else if (result.code !== responseEnum.NO_PERMISSION) {
        ElMessage.error(result.msg)
      }
      nProgress.done()
    }

    return {
      ...toRefs(coreData),
      fileSelect,
      cancel,
      confirm
    }
  }
})
</script>

<style lang='scss' scoped>
.upload-demo {
  text-align: right;
}
</style>
